#include "qbuddyface.h"
#include "qevent.h"
#include "txtool.h"
#include "immgr.h"

const int cIconSize = 40;
QIcon* qbuddyface::headImage[67][4];

qbuddyface::qbuddyface(QWidget *parent, UINT64 _uin, bool _bGroup)
	: QWidget(parent)
	, uin(_uin)
	, bGroup(_bGroup)
	, direction(0)
{
	pBtn = new QPushButton(this);
	connect(pBtn, SIGNAL(pressed()), this, SLOT(OnDbClick()));

	pLable = new QLabel(this);

	if (!headImage[1][1]) {
		for (int y = 1; y <= 66; ++y) {
			for (int x = 1; x <= 3; ++x) {
				st_str str;
				Util::Convert::IntToString(y, str);
				QString nA = "C:\\face\\";
				nA += str.c_str();
				nA += "-";
				Util::Convert::IntToString(x, str);
				nA += str.c_str();
				nA += ".bmp";

				headImage[y][x] = new QIcon(QPixmap(nA));
			}
		}
	}
}

qbuddyface::~qbuddyface()
{
	if (pBtn)
		delete pBtn;
	if (pLable)
		delete pLable;
}

void qbuddyface::setText(const QString & text)
{
	if (pLable) {
		pLable->setText(text);
		pLable->setAlignment(Qt::AlignHCenter);
	}
}

void qbuddyface::setHead( WORD wID )
{
	if (pBtn) {
		pBtn->setIconSize(QSize(cIconSize+2, cIconSize+2));
		pBtn->setIcon(*headImage[wID+1][1]);
	}
}

void qbuddyface::resizeEvent( QResizeEvent * event )
{
	const QSize & sz = event->size();

	pBtn->resize(cIconSize, cIconSize);
	pLable->resize(sz.width(), cIconSize/2);

	int dxdy[4][2] = {
		-5, +5,
		0, 0,
		+5, +5,
		0, 0,
	};

	pBtn->move((sz.width()-cIconSize)/2+dxdy[direction][0], 5+dxdy[direction][1]);
	pLable->move(0+dxdy[direction][0], cIconSize+5+dxdy[direction][1]);

	QWidget::resizeEvent(event);
}

void qbuddyface::OnDbClick()
{
	if (!bGroup)
		immgr::getInstance()->openChatFrame(uin);
	//else

}

void qbuddyface::setShark( bool bShark )
{
	if (bShark) {
		nTimerID = startTimer(300);
	}
	else {
		killTimer(nTimerID);
		QSize sz = size();
		int dxdy[4][2] = {
			-5, +5,
			0, 0,
			+5, +5,
			0, 0,
		};

		pBtn->move((sz.width()-cIconSize)/2, 5);
		pLable->move(0, cIconSize+5);
	}
}

UINT64 qbuddyface::getUin()
{
	return uin;
}

void qbuddyface::timerEvent( QTimerEvent *event )
{
	if (event->timerId() == nTimerID) {
		direction = (++direction)%4;

		QSize sz = size();
		int dxdy[4][2] = {
			-5, +5,
			0, 0,
			+5, +5,
			0, 0,
		};

		pBtn->move((sz.width()-cIconSize)/2+dxdy[direction][0], 5+dxdy[direction][1]);
		pLable->move(0+dxdy[direction][0], cIconSize+5+dxdy[direction][1]);
	}
	QWidget::timerEvent(event);
}